# Format:
# loop_date.sh yyyymmdd yyyymmdd {your program}
# Example 1:
# [IN]
# $ loop_date.sh 20210227 20210302 echo %s
# [OUT]
# $ 20210227
# $ 20210228
# $ 20210301
# $ 20210302
#
# Example 2:
# [IN]
# $ loop_date.sh 20210302 20210227 du -sh /remote/iosg/coin/data/flow/feed-05.ap-northeast-1.aws/%s/
# [OUT]
# $ 529G    /remote/iosg/coin/data/flow/feed-05.ap-northeast-1.aws/20210302/
# $ 513G    /remote/iosg/coin/data/flow/feed-05.ap-northeast-1.aws/20210301/
# $ 577G    /remote/iosg/coin/data/flow/feed-05.ap-northeast-1.aws/20210228/
# $ 543G    /remote/iosg/coin/data/flow/feed-05.ap-northeast-1.aws/20210227/

if [ "$#" -lt 3 ]; then
echo "Miss arguments.  example: bash loop_date.sh yyyymmdd yyyymmdd {your program}"
exit 1
fi

if [ -z "$1" ] || [ -z "$2" ] ; then
  echo "Wrong start/end date"
  exit 1
fi

reverse=false
if [ $1 -ge $2 ] ; then
  reverse=true
fi

if [ -z "$3" ]; then
  echo "No program"
  exit 1
fi

date=$1
ds=()
if $reverse
then
while [ $date -ge $2 ]
do
  ds+=($date)
  date=$(TZ="GMT" date -d "$date -1 day" "+%Y%m%d")
done
else
while [ $date -le $2 ]
do
  ds+=($date)
  date=$(TZ="GMT" date -d "$date +1 day" "+%Y%m%d")
done
fi

cmd="${@:3}"
for d in "${ds[@]}"
do
  #echo "$(printf "$cmd" $d)"
  $(printf "$cmd" $d)
done

exit 0